// pages/kecheng/kecheng.js
//导入token拦截函数
const request = require('../../utils/request').request;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageNo: 1,
    lunboArray: [],
    hasMore: true,
    remenArray: []
  },

//跳转至咨询公告页面
  toAnnouncementPage(){
    wx.navigateTo({
      url: '../kecheng_detail/announcement/announcement',
    })
  },

// 跳转至课程详情页
    toClassdetail(e) {
        const id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: '/pages/kecheng_detail/kechengxiangqing/kechengxiangqing?id=' + id
        });
    },
  kechengSearch(){
    wx.navigateTo({
      url: '../zhuye_detail/zhuye_search/zhuye_search',
    })
  },
  onlineClass(){
    wx.navigateTo({
      url: '../kecheng_detail/zaixiankecheng/zaixiankecheng',
    })
  },
  teacherTeam(){
    wx.navigateTo({
      url: '../kecheng_detail/shizituandui/shizituandui',
    })
  },

  // 处理价格数据，保留两位小数
  formatPrice(originalPrice, discount) {
    return (originalPrice * discount).toFixed(2);
  },

  // 加载热门课程
  loadHotCourses() {
    if (!this.data.hasMore) return;

    wx.showLoading({ title: '加载中' });

    wx.request({
      url: 'http://120.26.112.194:80/api/admin/courses/hot',
      method: 'GET',
      data: { page: this.data.pageNo, pageSize: 6 },
      success: (res) => {
        if (res.data && res.data.code === 200) {
          const newCourses = res.data.data.list.map(course => ({
            ...course,
            discountPrice: this.formatPrice(course.originalPrice, course.discount)
          }));
          this.setData({
            remenArray: this.data.pageNo === 1 ? newCourses : [...this.data.remenArray, ...newCourses],
            hasMore: res.data.data.hasNextPage,
            lunboArray:res.data.data.list
          });
          console.log(res.data.data.list)
        }
        wx.hideLoading();
      },
      fail: (error) => {
        console.error('请求失败', error);
        wx.hideLoading();
      }
    });
  },

    onLoad(options) {

    },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 页面显示时加载数据
    this.loadHotCourses();

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      pageNo: 1,
      hasMore: true
    }, () => {
      this.loadHotCourses();
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.hasMore) {
      this.setData({
        pageNo: this.data.pageNo + 1
      }, () => {
        this.loadHotCourses();
      });
    }
  }
})